<template>
  <a-modal
    :visible.sync="visible"
    width="1246px"
    title="版本管理"
    wrapClassName="versionManage-modal-container"
    @cancel="closeModal()"
    v-bind="footer"
    forceRender
    :maskClosable="false"
  >
    <div class="curve-modal-body">
      <div class="screen-header">
        <a-button
          class="cu-btn-primary"
          @click="handleVersionView()"
          :disabled="changeData.length == 2 ? false : true"
        >
          版本对比
        </a-button>
      </div>
      <div class="table-container">
        <vxe-table
          size="small"
          ref="xTree"
          align="center"
          height="99%"
          :data="tableData"
          :column-config="{ resizable: true }"
          :loading="loading"
        >
          <vxe-column width="60">
            <template #header> </template>
            <template #default="{ row, $rowIndex }">
              <a-checkbox
                :disabled="row.isDisabled"
                v-model="row.check"
                @change="changeItem($event, row, $rowIndex)"
              >
              </a-checkbox>
            </template>
          </vxe-column>
          <vxe-column field="name" title="版本名称"> </vxe-column>
          <vxe-column field="code" title="版本编号"> </vxe-column>
          <vxe-column field="createTimeStr" title="编制时间"> </vxe-column>
          <vxe-column field="typeDesc" title="计划类型"> </vxe-column>
          <vxe-column field="status" title="发布状态" width="100">
            <template #default="{ row }">
              <span :class="filterStatusClass(row.status)">
                {{ filterStatusType(row.status) }}
              </span>
            </template>
          </vxe-column>
          <vxe-column title="操作" fixed="right" width="400" align="left">
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button type="link" @click="handleEditor(row, 2)">
                  查看
                </a-button>
                <a-button
                  type="link"
                  v-show="row.submitFlag"
                  @click="handleEditor(row, 1)"
                  v-action="'edit_' + moduleSource()"
                >
                  编辑
                </a-button>
                <!--  -->
                <a-button
                  type="link"
                  @click="handleSubmit(row)"
                  :loading="submitLoading"
                  v-show="row.submitFlag"
                  v-action="'add_' + moduleSource()"
                >
                  提交
                </a-button>
                <a-button
                  type="link"
                  @click="handleRelease(row)"
                  :loading="releaseLoading"
                  v-show="row.publishFlag && row.status == 2"
                  v-action="'add_' + moduleSource()"
                >
                  发布
                </a-button>
                <a-button
                  type="link"
                  @click="handleApprove(row)"
                  v-show="row.approveFlag"
                >
                  审批
                </a-button>
                <a-button
                  type="link"
                  @click="handleApprovalRecord(row)"
                  v-show="isRecord(row)"
                >
                  审批记录
                </a-button>
                <a-button
                  type="link"
                  v-show="isRecord(row)"
                  @click="gotoFlow(row)"
                >
                  流程图
                </a-button>
                <a-button
                  type="link"
                  @click="handleDelClick(row)"
                  v-show="row.deleteFlag"
                  class="danger"
                  v-action="'delete_' + moduleSource()"
                >
                  删除
                </a-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
    <!-- 审批 -->
    <approveModal
      :visible.sync="approveModal.visible"
      :versionId="approveModal.id"
      @submit="refresh()"
    ></approveModal>
    <!-- 审批记录 -->
    <comment-modal ref="commentModal"></comment-modal>
    <!-- 流程图 -->
    <flowChat ref="flowChatForm"></flowChat>
  </a-modal>
</template>

<script>
//审批
import approveModal from "./approveModal.vue";
//审批记录
import commentModal from "@/pages/workflow/oaLeave/comment.vue";
//流程图
import flowChat from "@/pages/workflow/apiFlowableTask/myMission/flowChat.vue";
import {
  versionList,
  submitVersion,
  publishVersion,
  publishChildVersion,
  deleteVersion,
} from "@/api/progressManage";
export default {
  inject: ["moduleSource", "conditionsSource", "firstIndex"],
  components: {
    approveModal,
    commentModal,
    flowChat,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    footer: {
      type: Object,
      default() {
        return { footer: null };
      },
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      loading: false,
      tableData: [],
      //审批
      approveModal: {
        visible: false,
        id: "",
      },
      //发布
      releaseLoading: false,
      //提交
      submitLoading: false,
      //
      changeData: [],
    };
  },
  computed: {},
  methods: {
    refresh() {
      this.tableData = [];
      this.getData();
    },

    changeItem(event, row, index) {
      let { checked } = event.target;
      if (checked) {
        this.changeData = this.pushUniqueElement(this.changeData, row, index);
      } else {
        var _index = this.changeData.findIndex((v) => v.uuid == row.uuid);
        this.changeData.splice(_index, 1);
      }
      let ids = this.changeData.map((v) => v.uuid);
      if (this.changeData.length == 2) {
        this.tableData.forEach((item) => {
          if (ids.includes(item.uuid)) {
            item.isDisabled = false;
          } else {
            item.isDisabled = true;
          }
        });
      } else if (this.changeData.length < 2) {
        this.tableData.forEach((item) => {
          item.isDisabled = false;
        });
      } else if (this.changeData.length == 0) {
        this.tableData.forEach((item) => {
          item.isDisabled = false;
          item.check = false;
        });
      }
    },

    pushUniqueElement(array, newElement, index) {
      // 如果数组中已经有相同id的元素，先移除它
      const existingElement = array.find((el) => el.uuid === newElement.uuid);
      if (existingElement) {
        array.splice(array.indexOf(existingElement), 1); // 移除旧元素
      }
      // 将新元素添加到数组中
      array.push({
        sortIndex: index,
        uuid: newElement.uuid,
        publishVersionId: newElement.publishVersionId,
        parentVersionId: newElement.parentVersionId,
      });
      return array;
    },

    //版本对比
    handleVersionView() {
      let { tenantCode } = this.conditionsSource();
      this.changeData.sort((a, b) => a.sortIndex - b.sortIndex);
      let domain = location.origin;
      let newItem = this.changeData?.[1] ?? {};
      let oldItem = this.changeData?.[0] ?? {};
      window.open(
        `${domain}/#/design/planControl/versionComparison?nodeType=${this.moduleSource()}&proCode=${tenantCode ||
          ""}&newVersionId=${
          this.moduleSource() == "scheduleType.01"
            ? newItem.uuid
            : newItem.publishVersionId
        }&oldVersionId=${
          this.moduleSource() == "scheduleType.01"
            ? oldItem.uuid
            : oldItem.publishVersionId
        }`
      );
    },

    //审批
    handleApprove(row) {
      this.approveModal.id = row.uuid;
      this.approveModal.visible = true;
    },

    //审批记录
    handleApprovalRecord(row) {
      let id = "";
      if (row.type == "scheduleType.01") {
        id = row.uuid;
      } else {
        id = row.originalId;
      }
      this.$refs.commentModal.getCommentList(id);
    },

    //流程图
    gotoFlow(row) {
      let id = "";
      if (row.type == "scheduleType.01") {
        id = row.uuid;
      } else {
        id = row.originalId;
      }
      let record = JSON.parse(row?.flowData ?? "{}");
      this.$post("/workflow/oaLeave/clickFlowChart", {
        uuid: id,
      }).then((res) => {
        if (res.statusCode != 300) {
          const jsonData = res;
          this.$refs.flowChatForm.loadData(
            jsonData,
            jsonData.lists.actDeModelId,
            jsonData.lists.actDeModelKey,
            jsonData.lists.actDeModelName,
            jsonData.lists.flowDesign,
            record
          );
        } else {
          this.$message.error(res.message);
        }
      });
    },

    //编辑  1:编辑 2:查看
    handleEditor(row, type) {
      this.$emit("versionEditor", {
        source: row,
        operate: type,
      });
      this.$emit("update:visible", false);
    },

    //删除
    handleDelClick(row) {
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteVersion({ uuid: row.uuid, proCode: row.proCode })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                that.getData();
                that.firstIndex().getVersionData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },
    publishVersion,
    publishChildVersion,
    //发布
    handleRelease(row) {
      let that = this;
      let { uuid, proCode } = row;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定发布当前版本吗?",
        content: "",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FAAD14",
          }),
        onOk() {
          that.releaseLoading = true;
          that.$message.info("版本正在发布中，请耐心等待，请勿刷新页面");
          let url = "";
          if (that.moduleSource() == "scheduleType.01") {
            url = "publishVersion";
          } else {
            url = "publishChildVersion";
          }
          that[url]({ proCode, uuid, type: that.moduleSource() })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("发布成功", 1.5);
                that.closeModal();
                that.firstIndex().getVersionData();
              } else {
                that.$message.error(res?.message ?? "发布失败");
              }
            })
            .finally(() => {
              that.releaseLoading = false;
            });
        },
        onCancel() {},
      });
    },
    //提交
    handleSubmit(row) {
      let that = this;
      let { uuid } = row;
      let { tenantCode } = that.conditionsSource();
      const h = this.$createElement;
      this.$confirm({
        title: "您确定提交所选内容?",
        content: "",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FAAD14",
          }),
        onOk() {
          that.submitLoading = true;
          submitVersion({ uuid: uuid, proCode: tenantCode })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("提交成功", 1.5);
                that.getData();
              } else {
                that.$message.error(res?.message ?? "提交失败");
              }
            })
            .finally(() => {
              that.submitLoading = false;
            });
        },
        onCancel() {},
      });
    },
    getData() {
      this.loading = true;
      let { tenantCode, orgCode } = this.conditionsSource();
      return new Promise((resolve, reject) => {
        versionList({ proCode: tenantCode, orgCode, type: this.moduleSource() })
          .then((res) => {
            this.tableData = res?.data ?? [];
            this.tableData.forEach((v) => {
              if (v.type == "scheduleType.01") {
                this.$set(v, "check", false);
                // this.$set(v, "isDisabled", false);
              } else {
                this.$set(v, "check", false);
                // this.$set(v, "isDisabled", true);
              }
            });
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },
    //关闭弹窗
    closeModal() {
      this.changeData = [];
      //审批
      this.approveModal = {
        visible: false,
        id: "",
      };
      //审批记录
      this.approvalRecordModal = {
        visible: false,
        id: "",
      };
      //发布
      this.releaseLoading = false;
      //提交
      this.submitLoading = false;
      this.$emit("update:visible", false);
    },

    //审批记录权限
    isRecord(val) {
      if (val.status && val.status != 0 && val.flowData) {
        return true;
      } else {
        return false;
      }
    },

    //校验状态
    filterStatusType(val) {
      switch (Number(val)) {
        case -1:
          return "待提交";

        case 0:
          return "待提交";

        case 1:
          return "审批中";

        case 2:
          return "审批通过";

        case 3:
          return "驳回";

        case 4:
          return "已发布";

        case 5:
          return "已归档";

        default:
          return "";
      }
    },

    //校验状态
    filterStatusClass(val) {
      switch (Number(val)) {
        case 0:
          return "default";

        case 1:
          return "warning";

        case 2:
          return "progress";

        case 3:
          return "reject";

        case 4:
          return "success";

        case 5:
          return "place-file";

        default:
          return "";
      }
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.versionManage-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .curve-modal-body {
    box-sizing: border-box;
    padding: 20px 10px 10px 10px;
    height: 620px;
    display: flex;
    flex-direction: column;
    .screen-header {
      box-sizing: border-box;
      padding-bottom: 20px;
      .ant-btn.disabled,
      .ant-btn[disabled] {
        color: rgba(0, 0, 0, 0.25) !important;
        background-color: #f5f5f5 !important;
        border-color: #d9d9d9 !important;
      }
    }
    .table-container {
      flex: 1;
      .default {
        color: #8c8c8c;
      }
      .success {
        color: #4bc964;
      }
      .warning {
        color: #f07f17;
      }
      .reject {
        color: #ff3f4a;
      }
      .progress {
        color: #a07df1;
      }
      .place-file {
        color: #3b6bf5;
      }
    }
  }
}
</style>
